package com.ruoyi.blog.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.blog.domain.BlogArticleTag;
import com.ruoyi.blog.domain.BlogConfig;
import com.ruoyi.blog.domain.BlogTags;
import com.ruoyi.blog.domain.vo.ResultArchiveVo;
import com.ruoyi.blog.domain.vo.ResultArticleDetailVo;
import com.ruoyi.blog.domain.vo.ResultArticleListVo;
import com.ruoyi.blog.service.IBlogArticleTagService;
import com.ruoyi.blog.service.IBlogConfigService;
import com.ruoyi.blog.service.IBlogTagsService;
import com.ruoyi.blog.util.HtmlUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.blog.mapper.BlogArticleMapper;
import com.ruoyi.blog.domain.BlogArticle;
import com.ruoyi.blog.service.IBlogArticleService;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;

/**
 * 博客文章Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-05-05
 */
@Service
public class BlogArticleServiceImpl implements IBlogArticleService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(BlogArticleServiceImpl.class);

    @Autowired(required = false)
    private BlogArticleMapper blogArticleMapper;

    @Autowired
    private IBlogTagsService iBlogTagsService;

    @Autowired
    private IBlogArticleTagService iBlogArticleTagService;

    @Autowired
    private IBlogConfigService iBlogConfigService;

    @Autowired(required = false)
    private StringRedisTemplate redisCache;

    /**
     * 查询博客文章
     * 
     * @param id 博客文章ID
     * @return 博客文章
     */
    @Override
    public BlogArticle selectBlogArticleById(Long id)
    {
        return blogArticleMapper.selectBlogArticleById(id);
    }


    /**
     * 查询博客文章列表
     * 
     * @param blogArticle 博客文章
     * @return 博客文章
     */
    @Override
    public List<BlogArticle> selectBlogArticleList(BlogArticle blogArticle)
    {
        return blogArticleMapper.selectBlogArticleList(blogArticle);
    }

    @Override
    public List<ResultArticleListVo> selectBlogArticleList() {
        return blogArticleMapper.selectResultBlogArticleList();
    }


    /**
     * 新增博客文章
     * 
     * @param blogArticle 博客文章
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBlogArticle(BlogArticle blogArticle)
    {
        String text = HtmlUtil.delHtmlTags(blogArticle.getContent());
        blogArticle.setText(repText(text) );
        blogArticle.setCreateTime(DateUtils.getNowDate() );

        // 如果作者为空 那么取站点作者名称
        if (blogArticle.getAuthor() == null || "".equals(blogArticle.getAuthor()) ){
            BlogConfig blogConfig = iBlogConfigService.getBlogConfigByName("author");
            blogArticle.setAuthor(blogConfig.getValue().toString() );
        }

        blogArticleMapper.insertBlogArticle(blogArticle);
        int blogArticleId = Math.toIntExact(blogArticle.getId() );
        // 标签关联建立
        if (blogArticle.getTagsList() != null){
            String tagsStr = iBlogTagsService.addBlogArticleTags(blogArticle.getTagsList(), (long)blogArticleId);
            BlogArticle updateArticle = new BlogArticle();
            updateArticle.setTags(tagsStr.substring(0, tagsStr.length()-1) );

            QueryWrapper<BlogArticle> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", blogArticleId);
            blogArticleMapper.update(updateArticle, queryWrapper);
        }
        return blogArticleId;
    }

    /**
     * 修改博客文章
     * 
     * @param blogArticle 博客文章
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBlogArticle(BlogArticle blogArticle)
    {
        String text = HtmlUtil.delHtmlTags(blogArticle.getContent());
        blogArticle.setText(repText(text) );

        // 如果作者为空 那么取站点作者名称
        if (blogArticle.getAuthor() == null || "".equals(blogArticle.getAuthor()) ){
            BlogConfig blogConfig = iBlogConfigService.getBlogConfigByName("author");
            blogArticle.setAuthor(blogConfig.getValue().toString() );
        }

        // 删除原有标签关联
        iBlogArticleTagService.deleteBlogArticleTagByArticleId(blogArticle.getId() );
        // 标签关联建立
        if (blogArticle.getTagsList() != null && blogArticle.getTagsList().size() > 0){
            String tagsStr = iBlogTagsService.addBlogArticleTags(blogArticle.getTagsList(), (long)blogArticle.getId());
            BlogArticle updateArticle = new BlogArticle();
            updateArticle.setTags(tagsStr.substring(0, tagsStr.length()-1) );
            updateArticle.setId(blogArticle.getId() );
            blogArticleMapper.updateById(updateArticle);
        }
        return blogArticleMapper.updateBlogArticle(blogArticle);
    }

    /**
     * 批量删除博客文章
     * 
     * @param ids 需要删除的博客文章ID
     * @return 结果
     */
    @Override
    public int deleteBlogArticleByIds(Long[] ids)
    {
        return blogArticleMapper.deleteBlogArticleByIds(ids);
    }

    /**
     * 删除博客文章信息
     * 
     * @param id 博客文章ID
     * @return 结果
     */
    @Override
    public int deleteBlogArticleById(Long id)
    {
        return blogArticleMapper.deleteBlogArticleById(id);
    }


    public List<ResultArticleListVo> getArticleListByTypeName(String typeName) {
        return blogArticleMapper.selectArticleListByTypeName(typeName);
    }

    /**
     * 获取归档信息
     * @return
     */
    @Override
    public Map<String, Object> getArchive() {
        Map<String, Object> result = new HashMap<>();
        List<ResultArchiveVo> list = blogArticleMapper.selectBlogArchiveList();
        int count = blogArticleMapper.selectCount(null);
        result.put("list", list);
        result.put("count", count);
        return result;
    }


    /**
     * 接口查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResultArticleDetailVo selectApiBlogArticleById(Long id) {
        return blogArticleMapper.selectResultBlogArticleDetail(id);
    }

    private String repText (String content){
        String text = HtmlUtil.delHtmlTags(content);
        StringBuilder repText = new StringBuilder();
        if (text.length() >= 215){
            repText.append(text.substring(0,215) );
            repText.append("....");
        }else{
            return content;
        }
        return repText.toString();
    }

    /**
     * 添加访问量
     * @param articleId
     * @param ip
     */
    public void viewArticle(Long articleId, String ip) {
        String isViewKey = "isView:"+articleId;
        if (!redisCache.opsForHash().hasKey(isViewKey, ip) ){
            // 添加访问记录
            Map<String, Object> viewLogMap = new HashMap<>();
            viewLogMap.put("date", DateUtils.getNowDate() );
            redisCache.opsForHash().put(isViewKey, ip, viewLogMap.toString());
            // 添加访问量
            redisCache.opsForValue().increment("article:"+articleId, 1);
        }
    }

    /**
     *添加文章访问量
     * @param number
     * @param articleId
     * @return
     */
    @Override
    public Boolean incrArticleViewCount(int number, long articleId) {
        // 获取当前的访问量
        BlogArticle info = blogArticleMapper.selectById(articleId);
        if (info == null){
            LOGGER.debug("获取文章信息错误！");
            return false;
        }
        int viewCount = (info.getViewCount() == null ? 0 : info.getViewCount()) + number;

        BlogArticle blogArticle = new BlogArticle();
        blogArticle.setViewCount(viewCount);

        QueryWrapper<BlogArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", articleId);
        int result = blogArticleMapper.update(blogArticle, queryWrapper);

        return result > 0;
    }
}
